package me.askm.numcount;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class NumCountActivity extends Activity {
	
	private List<Integer> nums;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nums = new ArrayList<Integer>();
        
        final TextView outputText = (TextView) findViewById(R.id.result);
        final EditText inputText = (EditText) findViewById(R.id.inputNums);
        final Button countButton = (Button) findViewById(R.id.countButton);
        
        countButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				nums.clear();
				
				String input = inputText.getText().toString();
		        StringTokenizer tokens = new StringTokenizer(input, ".");
		        
		        while(tokens.hasMoreElements())
		        {
		        	nums.add(Integer.parseInt(tokens.nextElement().toString()));
		        }
		        
		        if(nums.size() == 0)
		        {
		        	outputText.setText("Please enter a search term");
		        	return;
		        }
		        
		        int findItem = nums.get(nums.size()-1);
		        nums.remove(nums.size()-1);
		        
		        int first = binSearch(findItem, nums, true);
		        int last = binSearch(findItem, nums, false);
		        
		        if(first == -1)
		        	outputText.setText("not found");
		        else
		        	outputText.setText((last - first + 1)+"");
			}
		});
    }

    private int binSearch(int i, List<Integer> A, boolean beginSearch)
    {
    	int start = 0;
    	int end = A.size() - 1;
    	
    	while(true)
    	{
    		int current = (start + end) / 2;
    		
    		if(current < 0 || current > A.size() - 1)
    			return -1;//not found
    		
    		int currentValue = A.get(current);
    		
    		if(!beginSearch &&  currentValue == i && (current >= (A.size()-1) || A.get(current+1) != i))
    			return current;
    		else if(beginSearch && currentValue == i && (current == 0 || A.get(current-1) != i))
    			return current;
    		else if(start == end)
    			return -1;
    		else if(beginSearch && i == currentValue)
    			end = current - 1;
    		else if(!beginSearch && i == currentValue)
    			start = current + 1;
    		else if(i < currentValue)
    			end = current - 1;
    		else if(i > currentValue)
    			start = current + 1;
    		
    		if(start > end)
    			break;
    	}
    	
    	return -1;
    }

    
}